package ml.uuku.swipeheadertabs.ui.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import ml.uuku.swipeheadertabs.R;
import ml.uuku.swipeheadertabs.adapter.SimpleStringListAdapter;
import ml.uuku.swipeheadertabs.ui.fragment.base.BaseSwipeRefreshLayout;

import android.support.design.widget.Snackbar;
import android.view.View;

/**
 * 作为一个示例，这里提供一个只展示简单字符串的列表，支持下拉刷新和上拉加载更多的功能
 * 
 * @author <a href=http://my.oschina.net/uuku>uuku</a>
 * @version V0.1
 */
public class SimpleStringListFragment extends BaseSwipeRefreshLayout {

    private SimpleStringListAdapter mListAdapter;
    private String[] data;

    @Override
    protected SimpleStringListAdapter getAdapter() {
        return mListAdapter;
    }

    @Override
    public void initData() {
        data = getActivity().getResources().getStringArray(R.array.book_list);
        mListAdapter = new SimpleStringListAdapter(mockData(20));
        mListAdapter.setOnItemClickListener(new SimpleStringListAdapter.OnItemClickListener() {
            @Override
            public boolean onItemClick(View view, Object data) {
                if (data != null) {
                    Snackbar.make(view, (String) data, Snackbar.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

    @Override
    protected void onRefreshData() {
        if (mSwipeRefreshLayout == null)
            return;
        mSwipeRefreshLayout.setRefreshing(true);
        // 模拟网络请求
        mSwipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mListAdapter.resetItems(mockData(20));
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    @Override
    protected void onLoadDataMore() {

        mSwipeRefreshLayout.setRefreshing(true);
        // 模拟网络请求
        mSwipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mListAdapter.appendItems(mockData(20));
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    private List<String> mockData(int count) {
        List<String> data = new ArrayList<String>(count);
        Random random = new Random();
        int length = this.data.length;
        while (data.size() < count) {
            data.add(this.data[random.nextInt(length)]);
        }
        return data;
    }

    /**
     * 为了解决SwipeRefreshLayout与CollapsingToolbarLayout共用时的事件冲突
     * <p>
     * 参考自: http://stackoverflow.com/questions/30779667/android-
     * collapsingtoolbarlayout-and-swiperefreshlayout
     * </p>
     * 
     * @param enable
     */
    public void setSwipeRefreshEnable(boolean enable) {
        mSwipeRefreshLayout.setEnabled(enable);
    }
}
